﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using RenderEngineInterfaces;

namespace SimpleFileRendering
{
    /// <summary>
    /// Render a web short cut file - turn it into a URL render.
    /// </summary>
    [Export(typeof(IRenderItem))]
    [RenderInfo(typeof(FileInfo))]
    public class WebShortCutRender : IRenderItem
    {
        /// <summary>
        /// Rendering engine to do sub-renders.
        /// </summary>
        [Import]
        public IRenderEngine MyRender { get; set; }

        /// <summary>
        /// Open up the website file, fish out the url, and then off let the render engine actually do
        /// the real work.
        /// </summary>
        /// <param name="what"></param>
        /// <returns></returns>
        public System.Threading.Tasks.Task<DeepZoomPivotConstructor.VisualLib.Visual> Render(object what)
        {
            var f = what as FileInfo;

            //
            // Get the line out of there that has the URL in it.
            //

            string line = "";
            using (var reader = f.OpenText())
            {
                while (!reader.EndOfStream)
                {
                    line = reader.ReadLine();
                    if (line.StartsWith("URL="))
                        break;
                }
            }

            if (!line.StartsWith("URL="))
                return null;

            string url = line.Substring(4);

            //
            // Now, convert to a URL
            //

            try
            {
                var u = new Uri(url);
                return MyRender.RenderToFuture(u);
            }
            catch { }

            return null;
        }

        /// <summary>
        /// See if the file exists and is the right type of file.
        /// </summary>
        /// <param name="what"></param>
        /// <returns></returns>
        public RenderPluginPriority RenderPriority(object what)
        {
            var f = what as FileInfo;
            if (!f.Exists)
                return RenderPluginPriority.RPPCantDoIt;

            if (f.Extension != ".website" && f.Extension != ".url")
                return RenderPluginPriority.RPPCantDoIt;

            return RenderPluginPriority.RPPGeneric;
        }
    }
}
